package com.zhen.aikan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zhen.aikan.constant.RedisConstants;
import com.zhen.aikan.entity.User;
import com.zhen.aikan.mapper.UserMapper;
import com.zhen.aikan.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhen.aikan.util.RedisUtils;
import com.zhen.aikan.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lijiazhen
 * @since 2023-09-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    public boolean existId(String id) {
        return exists(new QueryWrapper<User>().eq("user_id", id));
    }

    @Override
    public boolean existEmail(String email) {
        return exists(new QueryWrapper<User>().eq("email", email));
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean register(User user) {
        String s = RandomUtil.randomString(8);
        //注册时间
        user.setJoinDate(LocalDateTime.now());
        user.setUserName("用户" + s);
        return save(user);
    }

    @Override
    public boolean retrievePassword(UserVo userVo) {
        if (BeanUtil.isEmpty(userVo)) {
            return false;
        }
        User user = baseMapper.selectOne(new QueryWrapper<User>().eq("email", userVo.getId()));
        if (BeanUtil.isEmpty(user)) {
            return false;
        }
        user.setPassword(userVo.getPassword());
        return updateById(user);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateUser(User user, String token) {
        //更新数据库信息
        int update = baseMapper.update(user, new UpdateWrapper<User>().eq("user_id", user.getUserId()));
        if (update <= 0) {
            return false;
        }
        //更新redis里的用户信息
        User fullUser = baseMapper.selectOne(new QueryWrapper<User>().eq("user_id", user.getUserId()));
        if(BeanUtil.isEmpty(fullUser)){
            throw new RuntimeException();
        }
        //去除密码
        fullUser.setPassword("");
        Map<String, Object> userMap = RedisUtils.setUserMap(fullUser, token);
        if(userMap == null){
            throw new RuntimeException();
        }
        return true;
    }
}
